package com.lambkit.module.devops;

import cn.hutool.core.util.StrUtil;
import com.lambkit.devops.DevopsKit;
import com.lambkit.devops.DevopsLogDbTask;
import com.lambkit.devops.SqliteOpt;
import com.lambkit.module.LambkitModule;
import com.lambkit.util.FileKit;

import java.io.File;

public class DevopsModule extends LambkitModule {
	
	public void onStart() {
		String filePathAndName = "./lambkit/config.db";
		FileKit.createDirectory("./lambkit/");
		File file = new File(filePathAndName);
		SqliteOpt sqliteOpt = DevopsKit.getSqliteOperate();
		if (!file.exists()) {
			initSqlite(sqliteOpt, filePathAndName);
		}
		sqliteOpt.start("devops", filePathAndName);
		DevopsKit.setConfig("lambkit.devops.name", "devops");
		DevopsKit.setConfig("lambkit.devops.db", filePathAndName);
		
		String value = DevopsKit.getSetting("lambkit.devops.logdbtask");
		if("true".equals(value)) {
			DevopsLogDbTask logDbTask = new DevopsLogDbTask();
			logDbTask.onStart();
		}
	}

	public void onStop() {
		SqliteOpt sqliteOpt = DevopsKit.getSqliteOperate();
		sqliteOpt.stop("devops");
		//DevopsKit.setConfig("lambkit.devops.name", null);
		
		String devopsLog = DevopsKit.getConfig("lambkit.devops.logname");
		if(StrUtil.isNotBlank(devopsLog)) {
			sqliteOpt.stop(devopsLog);
			//DevopsKit.setConfig("lambkit.devops.logname", null);
		}
	}

	public void initSqlite(SqliteOpt sqliteOpt, String filePathAndName) {
		sqliteOpt.setConnection(filePathAndName);
		
		//配置表
		String sql1 = "CREATE TABLE IF NOT EXISTS devops_setting (\n" 
				+ "	setting_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n"
				+ "	setting_key TEXT NOT NULL,\n" 
				+ "	setting_value TEXT,\n" 
				+ "	setting_name TEXT,\n" 
				+ "	bisys INTEGER DEFAULT 0,\n" 
				+ "	remark TEXT ,\n" 
				+ "	created TEXT\n" 
				+ ");";
		sqliteOpt.update(sql1);
		
		//系统表
		String sql2 = "CREATE TABLE IF NOT EXISTS devops_system (\n" 
				+ "	system_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n"
				+ "	title TEXT,\n" 
				+ "	code TEXT,\n" 
				+ "	url TEXT,\n" 
				+ "	path TEXT,\n" 
				+ "	curl TEXT,\n"
				+ "	cmd_start TEXT,\n"
				+ "	cmd_restart TEXT,\n"
				+ "	cmd_stop TEXT,\n"
				+ "	status INTEGER DEFAULT 0,\n" 
				+ "	remark TEXT ,\n" 
				+ "	created TEXT\n" 
				+ ");";
		sqliteOpt.update(sql2);
		
		sqliteOpt.endConnection();
	}
}
